/*
 * Copyright 2009 Jesse McLaughlin (nzjess@gmail.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.travelfusion.xmlclient.impl.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.travelfusion.xmlclient.util.TfXAPIUtil;
import org.travelfusion.xmlclient.util.TimeZoneDelta;

import com.google.inject.Singleton;

/**
 * Default server-side implementation of <code>TimeZoneDelta<code>.
 * 
 * @author Jesse McLaughlin (nzjess@gmail.com)
 */
@Singleton
public class DefaultTimeZoneDelta implements TimeZoneDelta {

  private static ThreadLocal<SimpleDateFormat> TIMEZONE_FORMAT = new ThreadLocal<SimpleDateFormat>() {
    protected SimpleDateFormat initialValue() {
      return new SimpleDateFormat("Z");
    }
  };

  private long currentTZDeltaNextUpdate = -1;
  private int currentTZDelta;

  public int getTZDeltaMinutes() {
    final long now = System.currentTimeMillis();
    if (currentTZDeltaNextUpdate < now) {
      final Date date = new Date(now);
      String str = TIMEZONE_FORMAT.get().format(date);
      if (str.charAt(0) == '+') str = str.substring(1);
      currentTZDelta = Integer.parseInt(str) / 100 * 60;
      currentTZDeltaNextUpdate = TfXAPIUtil.midnight(date, 1).getTime();
    }
    return currentTZDelta;
  }
}
